package com.example.demo8;

import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import java.util.List;

public class Enemy {
    public double x, y;
    public final int type;
    public int health;
    public final Color color;
    public final int maxHealth;
    public final double speed;
    public final int damage;
    public int shootTimer;
    public static final int ENEMY_SIZE = 30;

    public Enemy(double x, double y, int type, Color color,
                 int maxHealth, double speed, int damage, int shootCooldown) {
        this.x = x;
        this.y = y;
        this.type = type;
        this.color = color;
        this.maxHealth = maxHealth;
        this.speed = speed;
        this.damage = damage;
        this.shootTimer = shootCooldown;
        this.health = maxHealth;
    }

    // 更新敌人状态，包括移动和射击
    public void update(double playerX, double playerY, CollisionSystem collisionSystem, List<Projectile> projectiles) {
        double dx = playerX - this.x;
        double dy = playerY - this.y;
        double dist = Math.hypot(dx, dy);

        if (dist > 0) {
            dx /= dist;
            dy /= dist;

            double newX = this.x + dx * this.speed;
            double newY = this.y + dy * this.speed;

            if (!collisionSystem.checkWallCollision(newX, newY, ENEMY_SIZE / 2)) {
                this.x = newX;
                this.y = newY;
            }
        }

        if (shootTimer > 0) shootTimer--;

        // 发射子弹
        if (dist < 300 && shootTimer <= 0) {
            shoot(playerX, playerY, projectiles);
            shootTimer = 120;  // 设置射击冷却时间
        }
    }

    private void shoot(double playerX, double playerY, List<Projectile> projectiles) {
        double angle = Math.atan2(playerY - this.y, playerX - this.x);
        double speed = 5;  // 子弹速度
        double dx = Math.cos(angle) * speed;
        double dy = Math.sin(angle) * speed;

        projectiles.add(new Projectile(this.x, this.y, dx, dy, this.damage / 2, true));  // 发射敌人的子弹
    }

    // 绘制敌人
    public void draw(GraphicsContext gc) {
        gc.setFill(color);
        gc.fillOval(x - ENEMY_SIZE / 2, y - ENEMY_SIZE / 2, ENEMY_SIZE, ENEMY_SIZE);

        double barWidth = ENEMY_SIZE;
        double barHeight = 5;
        double barX = x - barWidth / 2;
        double barY = y - ENEMY_SIZE / 2 - 10;

        gc.setFill(Color.DARKRED);
        gc.fillRect(barX, barY, barWidth, barHeight);

        double healthPercent = (double) health / maxHealth;
        gc.setFill(Color.RED);
        gc.fillRect(barX, barY, barWidth * healthPercent, barHeight);

        gc.setStroke(Color.BLACK);
        gc.setLineWidth(1);
        gc.strokeRect(barX, barY, barWidth, barHeight);
    }

    public boolean isAlive() {
        return health > 0;
    }
}
